<?php
namespace Admin\Model;
use Think\Model;

class UserModel extends Model {
    

    
//用户表的自动验证
    protected $_validate =array(
        //-1,用户名格式错误
        array('username', '/^[a-zA-Z]\w{3,15}$/', '用户名格式错误',0 , 'regex'),
        //-2,密码长度4-30位
        array('password', '/^\w{4,20}$/', '密码字母开头长度4位以上', 0, 'regex'),
        //登录用户名长度
        array('username', '4,20', '用户名长度4-20位', self::EXISTS_VALIDATE, 'length'),
 
    );
    protected $_auto = array(
        
        array('password','md5',3,'function'),
        
    );

	//用户登录
	public function login($username,$password){
    	    $data =array(
    	        'username'=>$username,
    	        'password'=>$password,
    	    );
    	    //where条件
	        $map['username']=$username;
	        $map['state']=1;
    	    //判断密码是否正确
    	    $User = $this->field('id,username,password')->where($map)->find();
        	    if ($User['password'] == md5($password)) {
        	          //将记录写入到session中去
        	          $auth = array(
        	              'id'=>$User['id'],
        	              'name'=>$User['username'],
        	          );
        	          	
        	          //写入到session
        	          session('auth', $auth);
        	          return $User['id'];
        	          
        	    } else {
        	         return -9; //密码不正确
        	    }
	    }
     
     
     
     
}